package org.ysling.litemall.wx.service;
// Copyright (c) [ysling] [927069313@qq.com]
// [litemall-plus] is licensed under Mulan PSL v2.
// You can use this software according to the terms and conditions of the Mulan PSL v2.
// You may obtain a copy of Mulan PSL v2 at:
//             http://license.coscl.org.cn/MulanPSL2
// THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
// EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
// MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
// See the Mulan PSL v2 for more details.

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.ysling.litemall.core.utils.RegexUtil;
import org.ysling.litemall.core.utils.response.ResponseUtil;
import org.ysling.litemall.db.constant.GrouponConstant;
import org.ysling.litemall.db.constant.OrderConstant;
import org.ysling.litemall.db.domain.*;
import org.ysling.litemall.db.service.*;
import org.ysling.litemall.db.vomain.CatVo;

import java.math.BigDecimal;
import java.util.*;

@Slf4j
@Service
public class WxBrandService {

    @Autowired
    private LitemallGoodsService goodsService;
    @Autowired
    private LitemallGoodsSpecificationService specificationService;
    @Autowired
    private LitemallGoodsAttributeService attributeService;
    @Autowired
    private LitemallGoodsProductService productService;
    @Autowired
    private LitemallCategoryService categoryService;
    @Autowired
    private LitemallGrouponRulesService rulesService;
    @Autowired
    private LitemallBrandService brandService;
    @Autowired
    private LitemallUserService userService;
    @Autowired
    private LitemallOrderService orderService;
    @Autowired
    private LitemallOrderGoodsService orderGoodsService;
    @Autowired
    private LitemallGrouponService grouponService;


    private Object validate(LitemallBrand brand) {
        if (brand == null) {
            return ResponseUtil.badArgument();
        }
        String name = brand.getName();
        String picUrl = brand.getPicUrl();
        String desc = brand.getDesc();
        String mail = brand.getMail();
        String userName = brand.getUserName();
        BigDecimal price = brand.getFloorPrice();
        if (!ObjectUtils.allNotNull(name, desc, picUrl, mail, price, userName)) {
            return ResponseUtil.badArgument();
        }
        if (RegexUtil.isUsername(mail)) {
            return ResponseUtil.badArgument();
        }
        if (price.compareTo(BigDecimal.ZERO) <= 0) {
            return ResponseUtil.badArgument();
        }
        if (brand.getId() == null && brandService.findByBrandName(brand.getName()) != null){
            return ResponseUtil.fail("店铺名称已存在");
        }
        return null;
    }


    public Object brandDetail(Integer brandId) {
        LitemallBrand brand = brandService.findById(brandId);
        if (brand == null) {
            return ResponseUtil.badArgumentValue();
        }
        Integer userId = brand.getUserId();
        HashMap<String, Object> dataMap = new HashMap<>();
        dataMap.put("brand",brand);
        if (userId != null){
            dataMap.put("brandUser",userService.findById(userId));
        }
        return ResponseUtil.ok(dataMap);
    }


    public Object brandSave(Integer userId, LitemallBrand brand) {
        if (Objects.isNull(userId)) {
            return ResponseUtil.unlogin();
        }

        Object error = validate(brand);
        if (error != null) {
            return error;
        }

        if (brand.getStatus() != null && !brand.getStatus().equals((byte)0)){
            return ResponseUtil.fail("店铺已禁用");
        }

        List<LitemallBrand> brands = brandService.queryByUserId(userId);
        if (brands.size() > 1) {
            return new RuntimeException("系统异常");
        }

        if (Objects.equals(1,brands.size())){
            //更新店铺信息
            if (brandService.updateVersionSelective(brand) == 0) {
                return ResponseUtil.updatedDataFailed();
            }
        }else {
            brand.setUserId(userId);
            brandService.add(brand);
        }
        LitemallUser user = new LitemallUser();
        user.setId(userId);
        user.setTrueName(brand.getUserName());
        userService.updateById(user);
        return ResponseUtil.ok(brand);
    }


    public Object orderList(Integer userId ,Integer showType, Integer page, Integer limit, String sort, String order) {
        if (Objects.isNull(userId)) {
            return ResponseUtil.unlogin();
        }

        List<LitemallBrand> brandList = brandService.queryByUserId(userId);
        if (brandList.size() != 1){
            return ResponseUtil.fail(800,"未找到店铺");
        }

        LitemallBrand brand = brandList.get(0);
        List<Short> orderStatus = OrderConstant.brandOrderStatus(showType);
        List<LitemallOrder> orderList = orderService.queryByBrandOrderStatus(brand.getId(), orderStatus, page, limit , sort , order);

        List<Map<String, Object>> orderVoList = new ArrayList<>(orderList.size());
        for (LitemallOrder o : orderList) {
            LitemallOrderGoods orderGoods = orderGoodsService.getByOrderId(o.getId());
            //拼装订单信息
            Map<String, Object> orderVo = new HashMap<>();
            orderVo.put("id", o.getId());
            orderVo.put("orderSn", o.getOrderSn());
            orderVo.put("address", o.getAddress());
            orderVo.put("actualPrice", o.getActualPrice());
            orderVo.put("addTime",orderGoods.getAddTime());
            orderVo.put("orderStatusText", OrderConstant.orderStatusText(o));
            orderVo.put("aftersAleStatus",o.getAftersaleStatus());
            LitemallGroupon groupon = grouponService.queryByOrderId(o.getId());
            orderVo.put("groupon", groupon);
            if (groupon != null) {
                orderVo.put("isGroupon", true);
                orderVo.put("refund", groupon.getStatus().equals(GrouponConstant.STATUS_FAIL));
                orderVo.put("ship", groupon.getStatus().equals(GrouponConstant.STATUS_SUCCEED));
                orderVo.put("grouponStatus", GrouponConstant.GrouponStatusText(groupon));
            } else {
                orderVo.put("isGroupon", false);
                orderVo.put("ship", o.getOrderStatus().equals(OrderConstant.STATUS_PAY) ||
                        o.getOrderStatus().equals(OrderConstant.STATUS_BTL_PAY));
                orderVo.put("refund", o.getOrderStatus().equals(OrderConstant.STATUS_REFUND));
            }
            orderVo.put("goods", orderGoods);
            orderVoList.add(orderVo);
        }
        return ResponseUtil.okList(orderVoList,orderList);
    }


    public Object goodsList(Integer brandId, Integer page, Integer limit) {
        List<LitemallGoods> goodsList = goodsService.queryByBrand(brandId, page, limit);
        return ResponseUtil.okList(goodsList);
    }

    public Object catList() {
        // http://element-cn.eleme.io/#/zh-CN/component/cascader
        // 管理员设置“所属分类”
        List<LitemallCategory> l1CatList = categoryService.queryL1();
        List<CatVo> categoryList = new ArrayList<>(l1CatList.size());

        for (LitemallCategory l1 : l1CatList) {
            CatVo l1CatVo = new CatVo();
            l1CatVo.setValue(l1.getId());
            l1CatVo.setLabel(l1.getName());

            List<LitemallCategory> l2CatList = categoryService.queryByPid(l1.getId());
            List<CatVo> children = new ArrayList<>(l2CatList.size());
            for (LitemallCategory l2 : l2CatList) {
                CatVo l2CatVo = new CatVo();
                l2CatVo.setValue(l2.getId());
                l2CatVo.setLabel(l2.getName());
                children.add(l2CatVo);
            }
            l1CatVo.setChildren(children);
            categoryList.add(l1CatVo);
        }

        Map<String, Object> data = new HashMap<>();
        data.put("categoryList", categoryList);
        return ResponseUtil.ok(data);
    }

    public Object goodsDetail(Integer id) {
        LitemallGoods goods = goodsService.findById(id);
        if (goods == null){
            return ResponseUtil.fail(600,"商品不存在");
        }
        List<LitemallGoodsProduct> products = productService.queryByGid(id);
        List<LitemallGrouponRules> grouponRules = rulesService.queryByGoodsId(id);
        List<LitemallGoodsSpecification> specifications = specificationService.queryByGid(id);
        List<LitemallGoodsAttribute> attributes = attributeService.queryByGid(id);

        Integer categoryId = goods.getCategoryId();
        LitemallCategory category = categoryService.findById(categoryId);
        Integer[] categoryIds = new Integer[]{};
        if (category != null) {
            Integer parentCategoryId = category.getPid();
            categoryIds = new Integer[]{parentCategoryId, categoryId};
        }

        Map<String, Object> data = new HashMap<>();
        data.put("goods", goods);
        data.put("specifications", specifications);
        data.put("products", products);
        data.put("attributes", attributes);
        data.put("categoryIds", categoryIds);
        if (goods.getIsGroupon() && grouponRules.size()>0){
            data.put("grouponRules", grouponRules.get(0));
        }
        return ResponseUtil.ok(data);
    }

}